﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Compilation;

namespace MyClub.Web.Routing
{
    /// <summary>
    /// Provides logic for handling a route mapped to a virtual path.
    /// </summary>
    public class VirtualPathRouteHandler: RouteHandler
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="VirtualPathRouteHandler"/> class.
        /// </summary>
        /// <param name="virtualPath">The virtual path.</param>
        public VirtualPathRouteHandler(string virtualPath)
            {
            if (string.IsNullOrEmpty(virtualPath))
                throw new ArgumentNullException("virtualPath");

            VirtualPath = virtualPath;
        }

        /// <summary>
        /// Gets or sets the virtual path.
        /// </summary>
        /// <value>The virtual path.</value>
        public string VirtualPath { get; private set; }

        /// <summary>
        /// Creates the HTTP handler.
        /// </summary>
        /// <param name="requestContext">The request context.</param>
        /// <returns>
        /// An instance that implements the <see cref="IHttpHandler"/>.
        /// </returns>
        protected override IHttpHandler CreateHttpHandler(System.Web.Routing.RequestContext requestContext)
        {
            // Create an instance of the page.
            var httpHandler = BuildManager.CreateInstanceFromVirtualPath(VirtualPath, typeof(System.Web.IHttpHandler)) as System.Web.IHttpHandler;

            if (httpHandler == null)
                throw new InvalidOperationException();

            return httpHandler;
        }
    }
}
